package com.huan.social.baidu.api.impl;

import com.google.gson.Gson;
import com.huan.social.baidu.api.Baidu;
import com.huan.social.baidu.api.BaiduUserInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * 百度接口实现,此处用户获取用户在百度上的基本信息
 *
 * @author huan.fu
 * @date 2018/9/27 - 17:01
 */
@Slf4j
public class BaiduTemplate extends AbstractOAuth2ApiBinding implements Baidu {

	@Getter
	private String userInfoUrl;
	@Getter
	private String accessToken;

	public BaiduTemplate(String accessToken, String userInfoUrl) {
		/**
		 * 调用父类 2 个参数的构造方法，
		 * TokenStrategy.ACCESS_TOKEN_PARAMETER 父类会自动将此参数带上，默认是放在请求头Authorization头中
		 */
		super(accessToken, TokenStrategy.OAUTH_TOKEN_PARAMETER);
		this.userInfoUrl = userInfoUrl;
		this.accessToken = accessToken;
	}

	@Override
	public BaiduUserInfo getUserInfo() {
		String userInfo = getRestTemplate().getForObject(String.format(this.getUserInfoUrl(), this.getAccessToken()), String.class);
		log.info("获取的百度用户信息为:[{}]", userInfo);
		return new Gson().fromJson(userInfo, BaiduUserInfo.class);
	}
}
